﻿using System;
using System.Drawing;
using System.Windows.Forms;

namespace Imager
{
    /// <summary>
    /// Description of ImageComponent.
    /// </summary>
    public class TextComponent : ComponentOfImage
    {
        public Point Location { get; private set; }
        private string message_saver;
        private Control.ControlCollection collection;

        private string message
        {
            get { return message_saver; }
            set
            {
                this.border.Size = TextRenderer.MeasureText(value, drawingFont);
                message_saver = value;
            }
        }

        private TextBox textbox = null;
        private Button buttonOk = null;

        public Font Font
        {
            get { return drawingFont; }
            set
            {
                if (value != null)
                    drawingFont = value;
                this.border.Size = TextRenderer.MeasureText(message, drawingFont);
            }
        }

        public Color TextColor
        {
            set { this.brush = new SolidBrush(value); }
        }

        private Brush brush = Brushes.Black;

        private Font drawingFont;

        public TextComponent(int x, int y, Control.ControlCollection collection, Font font)
        {
            this.collection = collection;
            this.Resizeble = false;
            this.border = new Rectangle(x, y, 0, 0);
            this.drawingFont = font;
            StartEditText();
        }

        public void StartEditText()
        {
            if (textbox == null)
            {
                textbox = new TextBox();
                textbox.Location = this.border.Location;
                textbox.Font = drawingFont;
                textbox.Text = message;
                textbox.KeyDown += new KeyEventHandler(OnKeyDown);

                buttonOk = new Button();
                buttonOk.Text = "OK";
                buttonOk.Click += delegate { EndEditText(); };
                buttonOk.Top = textbox.Top;
                buttonOk.Height = textbox.Height;
                buttonOk.Left = textbox.Left + textbox.Width + 10;

                collection.Add(buttonOk);
                collection.Add(textbox);
                textbox.Focus();
            }
        }

        public void EndEditText()
        {
            this.message = this.textbox.Text;
            this.textbox.Dispose();
            this.buttonOk.Dispose();
            textbox = null;
            buttonOk = null;
        }

        private void OnKeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.EndEditText();
            }
        }

        public override void Draw(Graphics gr)
        {
            gr.DrawString(message, drawingFont, brush, border.Location);
        }
    }
}